<?php

namespace app\api\controller;

use app\common\controller\Common;

class Firmware extends Common
{
    //列表
    public function index()
    {
        $param = input('param.');
        $result = Model('Firmware')->list($param);
        return resultArray(['data' => $result]);
    }

    //创建
    public function store()
    {
        if (!request()->isPost()) {
            return resultArray(['error' => '上传类型错误']);
        }

        try {
            //文件上传
            $file = request()->file('file');
            if (!$file) {
                return resultArray(['error' => '文件上传失败']);
            }
            //移动文件
            $info = $file->validate(['ext' => 'bin'])->move(config('huisheng.firmware_path'));
            if (!$info) {
                var_dump($file->getError());
                return resultArray(['error' => '文件处理失败']);
            }
            //保存数据库
            $model = Model('Firmware');
            $param = input('param.');
            $param['update_url'] = $info->getSaveName();
            if (!$model->createData($param)) {
                unlink(config('huisheng.firmware_path') . $param['update_url']);
                return resultArray(['error' => '保存失败']);
            }
            return resultArray(['data' => '']);
        } catch (\Exception $e) {
            return resultArray(['error' => '保存失败']);
        }
    }

    //更新
    public function update(){
        $param = input('param.');
        $id = $param['id'];
        //unset($param['id']);
        $model = Model('Firmware');
        $result = $model->updateDataById($param, $id);
        if(!$result){
            //return resultArray(['error' => $model->getError()]);
            return resultArray(['error' => '请求错误']);
        }
        return resultArray(['data' => '']);
    }

    //检查
    public function check($version)
    {
        try {
            $ori = Model("Firmware")->get(['version' => $version]);
            $latest = Model("Firmware")->where('status', 1)->order('id desc')->limit(1)->find();
            //判断源版本是否大于最新版版本
            if ($ori->id != $latest->id) {
                $latest->update_status = 1;
            } else {
                $latest->update_status = 0;
            }
            return resultArray(['data' => $latest]);
        } catch (\Exception $e) {
            return resultArray(['error' => '调用失败']);
        }
    }

    //下载
    public function download($url){
        $path = config('huisheng.firmware_path') . DS . $url;
        if (is_file($path)) {
            download_result_one($path);
        } else {
            return resultArray(['error' => '文件不存在']);
        }
    }
}
